<template>
  <div class="package-edit-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>编辑商品</span>
          <el-button type="primary" @click="handleSubmit">保存操作</el-button>
        </div>
      </template>

      <el-tabs v-model="activeTab" type="border-card">
        <!-- 基本信息Tab -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="basicFormRef" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="关联类型" prop="goods.relatedType">
              <el-select
                @change="handleChangeRelatedType"
                v-model="formData.goods.relatedType"
                :disabled="!!formData.goods.id"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in GoodsRelatedType"
                  :key="item"
                  :label="GoodsRelatedType_LABEL[item]"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="关联材料"
              prop="goods.relatedName"
              v-if="formData.goods.relatedType === GoodsRelatedType.Material"
            >
              <el-autocomplete
                v-model="formData.goods.relatedName"
                :disabled="!!formData.goods.id"
                clearable
                :fetch-suggestions="queryMaterial"
                value-key="label"
                placeholder="请选择关联材料"
                @select="handleMaterialSelect"
              ></el-autocomplete>
            </el-form-item>
            <el-form-item
              label="关联套餐"
              prop="goods.relatedName"
              v-if="formData.goods.relatedType === GoodsRelatedType.SaleMeal"
            >
              <el-autocomplete
                v-model="formData.goods.relatedName"
                :disabled="!!formData.goods.id"
                clearable
                :fetch-suggestions="querySaleMeal"
                value-key="label"
                placeholder="请选择关联套餐"
                @select="handleMaterialSelect"
              ></el-autocomplete>
            </el-form-item>
            <el-form-item label="商品名称" prop="goods.name" required>
              <el-input v-model="formData.goods.name" placeholder="请输入商品名称" />
            </el-form-item>
            <el-form-item label="商品分类" prop="goods.categoryId" required>
              <el-tree-select
                v-model="formData.goods.categoryId"
                placeholder="请选择所属分类"
                :data="categoryOptions"
                filterable
                check-strictly
                :render-after-expand="false"
              />
            </el-form-item>
            <el-form-item label="商品编码" prop="code">
              <el-input v-model="formData.goods.code" placeholder="请输入商品编码，否则自动生成" />
            </el-form-item>
            <el-form-item label="价格" prop="goods.price" required>
              <el-input-number
                v-model="formData.goods.price"
                :precision="2"
                :step="1"
                :min="0.01"
                style="width: 180px"
              >
                <template #prefix>
                  <span>￥</span>
                </template>
              </el-input-number>
            </el-form-item>
            <el-form-item label="折扣价格" prop="goods.discountPrice">
              <el-input-number
                v-model="formData.goods.discountPrice"
                :precision="2"
                :step="1"
                :min="0.01"
                style="width: 180px"
              >
                <template #prefix>
                  <span>￥</span>
                </template>
              </el-input-number>
            </el-form-item>
            <el-form-item label="商品品牌" prop="goods.brand">
              <el-input v-model="formData.goods.brand" placeholder="请输入商品品牌" />
            </el-form-item>
            <el-form-item label="商品型号" prop="model">
              <el-input v-model="formData.goods.model" placeholder="请输入商品型号" />
            </el-form-item>
            <el-form-item label="商品单位" prop="unit">
              <el-input v-model="formData.goods.unit" placeholder="请输入商品单位" />
            </el-form-item>
            <el-form-item label="厂家" prop="company">
              <el-input v-model="formData.goods.company" placeholder="请输入商品厂家" />
            </el-form-item>
            <el-form-item label="商品简介" prop="goods.brief">
              <el-input v-model="formData.goods.brief" placeholder="请输入商品简介" />
            </el-form-item>
            <el-form-item label="图片">
              <MultiImageUpload
                :model-value="formData.imageIds"
                :data="fileBusiness"
                :limit="3"
                :file-types="['image/jpeg', 'image/png']"
                :max-size="2"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 参数信息Tab -->
        <el-tab-pane label="参数信息" name="params">
          <div v-if="!formData.spus || formData.spus.length === 0">
            <el-button
              type="primary"
              plain
              @click="formData.spus = [{ property: '', propertyValue: '' }]"
            >
              添加商品参数
            </el-button>
          </div>

          <div style="padding: 5px 10px" v-else>
            <div v-for="(item, index) in formData.spus" :key="index" class="spus-line">
              <el-input v-model="item.property" placeholder="参数名称" style="width: 120px" />
              <span class="mx-1">：</span>
              <el-input v-model="item.propertyValue" placeholder="参数值" style="width: 300px" />
              <el-button
                class="ml-2"
                size="small"
                type="primary"
                link
                icon="CirclePlusFilled"
                @click="formData.spus.splice(index + 1, 0, { property: '', propertyValue: '' })"
              >
                添加
              </el-button>
              <el-button
                size="small"
                link
                icon="ArrowUp"
                :disabled="index === 0"
                @click="
                  [formData.spus[index - 1], formData.spus[index]] = [
                    formData.spus[index],
                    formData.spus[index - 1],
                  ]
                "
              >
                上移
              </el-button>
              <el-button
                size="small"
                link
                icon="ArrowDown"
                :disabled="index == formData.spus.length - 1"
                @click="
                  [formData.spus[index + 1], formData.spus[index]] = [
                    formData.spus[index],
                    formData.spus[index + 1],
                  ]
                "
              >
                下移
              </el-button>
              <el-button
                size="small"
                type="danger"
                link
                icon="DeleteFilled"
                @click="formData.spus.splice(formData.spus.indexOf(item), 1)"
              >
                删除
              </el-button>
            </div>
          </div>
        </el-tab-pane>

        <!-- SKU信息Tab -->
        <el-tab-pane label="移动端页面" name="h5">
          <WangEditor v-if="activeTab == 'h5'" v-model="formData.goods.h5" height="400px" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";
import GoodsAPI, {
  SumbitGoodsForm,
  GoodsRelatedType,
  GoodsRelatedType_LABEL,
} from "@/api/goods/goods.api";
import MaterialAPI from "@/api/business/material/material.api";
import CategoryAPI from "@/api/goods/category.api";
import WangEditor from "@/components/WangEditor/index.vue";
import { cloneDeep } from "lodash-es";

defineOptions({
  name: "GoodsEdit",
  inheritAttrs: false,
});

const route = useRoute();
const fileBusiness = reactive<object>({
  businessType: "goods",
});
const goodsId = ref("");

const rules = reactive({
  "goods.name": [{ required: true, message: "商品名不能为空", trigger: "blur" }],
  "goods.brief": [{ required: true, message: "商品简介不能为空", trigger: "blur" }],
  "goods.brand": [{ required: true, message: "品牌不能为空", trigger: "blur" }],
  "goods.categoryId": [{ required: true, message: "商品分类不能为空", trigger: "blur" }],
  "goods.relatedType": [{ required: true, message: "关联类型不能为空", trigger: "blur" }],
  "goods.price": [{ required: true, message: "商品价格不能为空", trigger: "blur" }],
  "goods.relatedName": [{ required: true, message: "请选择关联的材料或套餐", trigger: "blur" }],
});

// 分类下拉数据源
const categoryOptions = ref<OptionType[]>();
const basicFormRef = ref();
const activeTab = ref("basic");
const loading = ref(false);
const materialOptions = ref<OptionType[]>([]);
const saleMealOptions = ref<OptionType[]>([]);

const defaultFormData = {
  goods: { h5: "", relatedType: GoodsRelatedType.Material },
  spus: [],
  imageIds: [],
  attrs: [],
  skus: [],
};
const formData = reactive<SumbitGoodsForm>(cloneDeep(defaultFormData));

onActivated(() => {
  if (route.query.goodsId == goodsId.value) return;
  // id变动 重置数据
  goodsId.value = route.query.goodsId as string;
  clear();
  loadGoodsDetail(goodsId.value);
});

// 加载商品详情
const loadGoodsDetail = async (id?: string) => {
  if (!id || id === "0") {
    return;
  }
  await GoodsAPI.getFormData(id).then((data) => {
    Object.assign(formData, { ...data });

    // 确保 h5 字段为字符串类型
    if (typeof formData.goods.h5 !== "string" || !formData.goods.h5.trim()) {
      formData.goods.h5 = "";
    }
    const webFiles = data.attachments?.map((f) => f.id || "");
    formData.imageIds = webFiles;
  });
};

// 提交商品表单
const handleSubmit = () => {
  basicFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      if (formData.imageIds && formData.imageIds.length > 0) {
        formData.goods.imageId = formData.imageIds[0];
      }
      if (
        formData.goods.discountPrice &&
        formData.goods.price &&
        (formData.goods.discountPrice as number) - (formData.goods.price as number) >= 0
      ) {
        ElMessage.warning("折扣价不能高于市场价");
        return;
      }
      if (formData.goods.id) {
        GoodsAPI.update(formData)
          .then(() => {
            ElMessage.success("修改商品成功");
          })
          .finally(() => (loading.value = false));
      } else {
        GoodsAPI.create(formData)
          .then(() => {
            ElMessage.success("新增商品成功");
            clear();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
};

const queryMaterial = (queryString: string, cb: (arg: any) => void) => {
  if (!queryString) {
    return materialOptions.value;
  }
  const results = materialOptions.value.filter((item: OptionType) => {
    if (item.label && item.label.toLowerCase().indexOf(queryString.toLowerCase()) === 0) {
      return true;
    }
    return false;
  });
  cb(results);
};

const querySaleMeal = (queryString: string, cb: (arg: any) => void) => {
  if (!queryString) {
    return saleMealOptions.value;
  }
  const results = saleMealOptions.value.filter((item: OptionType) => {
    if (item.label && item.label.toLowerCase().indexOf(queryString.toLowerCase()) === 0) {
      return true;
    }
    return false;
  });
  cb(results);
};

const handleMaterialSelect = (item: Record<string, any>) => {
  formData.goods.relatedId = item.value;
};
const handleChangeRelatedType = () => {
  formData.goods.relatedId = undefined;
  formData.goods.relatedName = "";
};

const clear = () => {
  Object.assign(formData, cloneDeep(defaultFormData));
  activeTab.value = "basic";
};

// 加载商品分类
const loadGoodsCategory = () => {
  CategoryAPI.getOptions().then((data) => {
    if (data.length > 0) {
      categoryOptions.value = [];
      categoryOptions.value.push(...data);
    }
  });
};

// 加载材料/套餐备选
const loadAllOptions = async () => {
  materialOptions.value = await MaterialAPI.loadOptions(GoodsRelatedType.Material);
  saleMealOptions.value = await MaterialAPI.loadOptions(GoodsRelatedType.SaleMeal);
};

onMounted(() => {
  loadAllOptions();
  loadGoodsCategory();
});
</script>

<style scoped>
.package-edit-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.spus-line {
  margin-bottom: 5px;
  :deep(.el-button) {
    font-size: 0.8rem;
  }
  :deep(span) {
    margin-left: 1;
  }
}
</style>
